<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, nextTick, watch } from 'vue'
import { ElTree, ElInput } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import GisInfoApi from '@/api/gis/gisMap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import EditVue from './components/Edit.vue'
import { PointHook } from '../FacOutComponents/LedgerHooks'
import LedgerApi from '@/api/equip/ledger'
import { useEquipStore } from '@/store/modules/equip'
import { PipePointInfoType } from '@/api/gis/type'
import { BaseButton } from '@/components/Button'
const EquipStore = useEquipStore()
const { t } = useI18n()
const { crudSchemas } = PointHook()
const ActionCrudSchemas = {
  field: 'action',
  label: t('tableDemo.action'),
  width: 200,
  fixed: 'right',
  search: {
    hidden: true
  },
  form: {
    hidden: true
  },
  detail: {
    hidden: true
  },
  table: {
    slots: {
      default: (data: any) => {
        return (
          <>
            <span class="TableBtn" onClick={() => action(data.row, 'Edit')}>
              {t('修改')}
            </span>
            <span class="TableBtn" onClick={() => action(data.row, 'Detail')}>
              {t('查看')}
            </span>

            <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
              {t('删除')}
            </span>
          </>
        )
      }
    }
  }
}
crudSchemas.push(ActionCrudSchemas)
const ids = ref<string[]>([])
const treeEl = ref<typeof ElTree>() //树结构
const currentNodeKey = ref('') //树结构ID
const departmentList = ref<any>([]) //树结构数据

//表格内容接口
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const i = await GisInfoApi.GetPipePointList({
      faciIds: unref(FaciId).toString(),
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: i.rows,
      total: i.total
    }
  },
  fetchDelApi: async () => {
    const res = await LedgerApi.DeletLedger(unref(ids)[0])
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const FormDisabled = ref(true)
const FaciId = ref<string[]>([])
const { allSchemas } = useCrudSchemas(crudSchemas)
const fetchDepartment = async () => {
  if (
    EquipStore.getFacilityTypeTree.length == 0 ||
    EquipStore.getFacilityTypeTree.length == undefined
  ) {
    EquipStore.setFacilityTypeTree()
  }
  departmentList.value = EquipStore.getFacilityTypeTree
  currentNodeKey.value = String(EquipStore.getFacilityTypeTree[0].id) || '' //树结构ID也为第一个
  await nextTick()
  unref(treeEl)?.setCurrentKey(currentNodeKey.value) //应用到树结构
}
fetchDepartment() //获取树结构
const currentDepartment = ref('') //树结构搜索框内容
watch(
  () => currentDepartment.value, //监控树结构搜索框内容变化
  (val) => {
    unref(treeEl)!.filter(val)
  }
)
const currentChange = (data: any) => {
  //树结构点击
  const output = FaciId.value.find((object) => object == data.id)
  if (output) {
    FaciId.value = FaciId.value.filter((item) => item !== data.id)
  } else {
    FaciId.value.push(data.id)
  }
  currentNodeKey.value = data.id
  currentPage.value = 1 //页面为第一页
  getList() //表格更新
}
const filterNode = (value: string, data: any) => {
  //树结构变化
  if (!value) return true
  return data.label.includes(value)
}
const currentRow = ref<any>()
const saveLoading = ref(false)
const delLoading = ref(false)
//表格删除操作
const delData = async (row: PipePointInfoType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.uuid] : elTableExpose?.getSelectionRows().map((v: any) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')
const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}

//表格中操作
const action = (row: PipePointInfoType, type: string) => {
  actionType.value = type
  dialogVisible.value = true //打开弹窗
  if (type == 'add') {
    EquipStore.setEquipFormData({})
    EquipStore.FacilityByFacId = { formschema: [], current: {} }
    dialogTitle.value = '新增'
    FormDisabled.value = false
    currentRow.value = {}
  } else if (type == 'Edit') {
    EquipStore.setEquipFormData(row)
    dialogTitle.value = '修改'
    FormDisabled.value = false
    currentRow.value = row
    if (currentRow.value['file'] == null) {
      currentRow.value['file'] = []
    } else {
      if (!Array.isArray(currentRow.value['file'])) {
        currentRow.value['file'] = JSON.parse(currentRow.value['file'])
      }
    }
  } else if (type == 'Detail') {
    dialogTitle.value = '查看'
    FormDisabled.value = true
    currentRow.value = row
    if (!Array.isArray(currentRow.value['file'])) {
      currentRow.value['file'] = JSON.parse(currentRow.value['file'])
    }
  }
}
const EditRef = ref()
const save = async () => {
  const write = unref(EditRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    //新增任务组
    if (actionType.value == 'add') {
      res.value = await LedgerApi.AddFacilityLedger(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      //修改字
      res.value = await LedgerApi.EditFacilityLedger(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
</script>
<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px min-h-[580px]" title="类型">
      <ElInput
        v-model="currentDepartment"
        class="flex-[2] mb-[10px]"
        :placeholder="t('组织名称')"
        clearable
      />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        node-key="id"
        :show-checkbox="true"
        :check-strictly="true"
        default-expand-all
        :current-node-key="currentNodeKey"
        :props="{
          label: 'departmentName'
        }"
        :filter-node-method="filterNode"
        @check-change="currentChange"
      >
        <template #default="{ data }">
          <div :title="data.label" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
            {{ data.label }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px" title="设施台账">
      <!-- <div class="flex"> -->
      <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
        <Icon icon="ep:plus" :size="13" />新增
      </BaseButton>
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
      />
      <!-- </div> -->
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        row-key="uuid"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>
    <Dialog v-model="dialogVisible" :title="dialogTitle" maxHeight="500px" style="width: 1200px">
      <EditVue ref="EditRef" :current-row="currentRow" :FormDisabled="FormDisabled" />
      <template #footer v-if="actionType !== 'Detail'">
        <BaseButton type="primary" :loading="saveLoading" @click="save">
          {{ t('提交') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
<style scope>
/* .el-tree {
  height: 410px;
  overflow: hidden;
  overflow-y: scroll;
} */
.el-tree-node:focus > .el-tree-node__content {
  color: #409eff;
}
.el-card__body {
  padding: 10px;
  /* height: 90%; */
}
.CloseBtn {
  font-weight: 600;
  margin: 0 3px;
  color: darkgrey;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
.el-collapse-item {
  padding: 15px 0;
}
.el-collapse-item__content {
  padding-bottom: 0;
}
.el-collapse-item__header {
  width: 62px;
  height: 24px;
  border-radius: 2px;
  color: white;
  background: #409eff;
  justify-content: center;
  font-size: 12px;
}
.el-collapse-item__arrow {
  margin: 0 2px;
}

.TableBtn {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600;
}
</style>
@/views/GIS/OneMap/components/PointHooks @/api/gis/Pipnet@/api/gis/type
